﻿//************************************
// @FileName: RemoteClient.cs
// @Brief   : 远程客户端访问控制
// @Author  : Waterstrong
// @DateTime: 2012-11-7 9:27:22
//************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows;

namespace Server
{
    public class RemoteClient
    {
        private TcpClient _client;
        private NetworkStream _streamToClient;
        const int BufferSize = 8192; // 缓存大小
        private byte[] _buffer;
        // private RequestHandler handler;
        private MainWindow _win;
        public RemoteClient(TcpClient client, MainWindow win)
        {
            _win = win;
            _client = client;
            _streamToClient = client.GetStream();
            _buffer = new byte[BufferSize];
            AsyncCallback callBack = new AsyncCallback(ReceivePacket);
            _streamToClient.BeginRead(_buffer, 0, BufferSize, callBack, null);
        }

        void NewAction()
        {

        }

        /// <summary>
        /// 接收包
        /// </summary>
        /// <param name="ar"></param>
        /// <returns></returns>
        public void ReceivePacket(IAsyncResult ar)
        {
            int bytesRead = 0;
            try
            {
                lock (_streamToClient)
                {
                    bytesRead = _streamToClient.EndRead(ar);

                }
                if (bytesRead == 0)
                {
                    throw new Exception("读取到0字节");
                }

                Common.Packet packet = (Common.Packet)Common.Converter.Deserialize(_buffer);
                // string msg = Encoding.Unicode.GetString(_buffer, 0, bytesRead);
                Array.Clear(_buffer, 0, _buffer.Length); // 清空缓存
                //_win.rtb_msg.Dispatcher.Invoke(NewAction());

                _win.rtb_msg.Dispatcher.Invoke(new Action(() =>
                {
                    _win.rtb_msg.AppendText("Received : " + packet.Resource.ToString() + "\n");
                }));

                Common.Keyboard.Press(packet.InputKey);
                Common.Keyboard.Release(packet.InputKey);

                // 再次调用BeginRead，完成时调用自身
                lock (_streamToClient)
                {
                    AsyncCallback callBack = new AsyncCallback(ReceivePacket);
                    _streamToClient.BeginRead(_buffer, 0, BufferSize, callBack, null);
                }
            }
            catch (System.Exception ex)
            {
                if (_streamToClient != null)
                {
                    _streamToClient.Dispose();
                }
                _client.Close();
                MessageBox.Show("RemoteClient : " + ex.Message);
            }
        }
    }
}
